package cn.tedu.tmall.admin.content.service.impl;

import cn.tedu.tmall.admin.content.dao.persist.cache.ICategoryCacheRepository;
import cn.tedu.tmall.admin.content.dao.persist.repository.ICategoryRepository;
import cn.tedu.tmall.admin.content.service.ICategoryService;
import cn.tedu.tmall.common.pojo.po.CategoryPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private ICategoryCacheRepository cacheRepository;
    @Autowired
    private ICategoryRepository repository;
    @Override
    public List<CategoryPO> listByParentId(Long parentId) {
        List<CategoryPO> categoryList = cacheRepository.getCategoryList(parentId);
        if(categoryList==null){
            List<CategoryPO> categoryPOS = repository.listByParentId(parentId);
            cacheRepository.saveCategoryList(parentId,categoryPOS);
            return categoryPOS;
        }else {
            return categoryList;
        }
    }

    @Override
    public void rebuildCache() {
        cacheRepository.deleteAll();
        List<CategoryPO> categoryPOS = repository.listByParentId(0L);
        cacheRepository.saveCategoryList(0L,categoryPOS);
        for (CategoryPO categoryPO : categoryPOS) {
            recursion(categoryPO);
        }
    }
    private void recursion(CategoryPO categoryPO){
        if(categoryPO.getIsParent()==1){
            Long parentId = categoryPO.getId();
            List<CategoryPO> categoryPOS = repository.listByParentId(parentId);
            cacheRepository.saveCategoryList(parentId,categoryPOS);
            for (CategoryPO po : categoryPOS) {
                recursion(po);
            }
        }
        /*
        Long parentId = categoryPO.getId();
        List<CategoryPO> categoryPOS = repository.listByParentId(parentId);
        if(categoryPOS.size()>0){
            cacheRepository.saveCategoryList(parentId,categoryPOS);
            for (CategoryPO po : categoryPOS) {
                recursion(po);
            }
        }
         */
    }
}
